package cn.yunyichina.provider.drug.listener;

import cn.yunyichina.provider.drug.entity.Delivery;
import cn.yunyichina.provider.drug.service.impl.DeliveryServiceImpl;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.DrugService;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.base.Rule;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.drug.DeliveryVo;
import cn.yunyichina.provider.iface.entity.pay.notify.UnifiedPayNotifyMessage;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.listener.MessageListener;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 监听挂号支付成功后的kafka消息
 */
public class DrugAliPayMessageListener implements MessageListener<Integer, String> {

    private Logger logger = LoggerFactory.getLogger(DrugAliPayMessageListener.class);

    @Autowired
    private DeliveryServiceImpl deliveryService;

    public void onMessage(ConsumerRecord<Integer, String> integerStringConsumerRecord) {
        String jsonString = integerStringConsumerRecord.value();
        logger.info("【drug模块-支付宝支付监听】DrugAliPayMessageListener.onMessage.jsonString -> {}", jsonString);

        UnifiedPayNotifyMessage notifyMessage = JsonUtils.parseObject(jsonString, UnifiedPayNotifyMessage.class);
        String orderNo = notifyMessage.getOrderNo();
        BigDecimal payAmount = new BigDecimal(notifyMessage.getTotalAmount());//jsonObject.getBigDecimal("total_amount").multiply(new BigDecimal(100));
        String tradeNo = notifyMessage.getTradeNo();

        try {
            /**根据订单好查出订单对象**/
            Map<String, String> ordQueryMap = new HashMap<String, String>();
            ordQueryMap.put("order_no",orderNo);
            Response ordResponse = BaseService.callUnderlineFromInternal("",
                    "yyt.base.order.by.orderno.get", JsonUtils.toJsonString(ordQueryMap));
            if(!"0".equals(ordResponse.getResultCode())){
                logger.error("【drug模块-支付宝支付监听】查询订单失败 " + orderNo);
                return ;
            }
            OrderExtVo order = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
            if(order == null){
                logger.error("【drug模块-支付宝支付监听】查询订单为空 订单号=" +orderNo + ",ordResponse="+ JSON.toJSONString(ordResponse));
                return ;
            }

            order.setOrderType((short)10);
            order.setOrderStatus(OrderExtVo.ORDER_STATUS_WAIT_WRITE);
            order.setPayStatus(OrderExtVo.ORDER_PAY_STATUS_PAYED);
            order.setPayAmount(payAmount.intValue());
            order.setPayTime(notifyMessage.getPayTime());
            order.setOpenId(notifyMessage.getOpenId());
            order.setPaymentDealId(tradeNo);
            order.setPayAppId(notifyMessage.getAppId());
            BaseService.callUnderlineFromInternal("","yyt.base.order.update", JsonUtils.toJsonString(order));

            logger.info("【drug模块-支付宝支付监听】更新配送订单数据开始");

            Delivery delivery = deliveryService.selectByOrderNo(orderNo);
            delivery.setOrderStatus(DeliveryVo.ORDER_STATUS_PAYED);
            delivery.setPayTime(notifyMessage.getPayTime());
            delivery.setPaymentDealId(tradeNo);
            delivery.setPushFlag((short) 1);
            delivery.setUpdateTime(DateUtils.dateToString(new Date()));
            delivery.setOperationType((short) 0);
            delivery.setOperationResponse("支付宝支付监听-写单成功");
            deliveryService.updateDeliveryInner(delivery);
            logger.info("【drug模块-支付宝支付监听】" + orderNo + "写单成功");
            deliveryService.sendNewOrderSms(delivery);
            logger.info("【drug模块-支付宝支付监听】" + orderNo + "发送新订单短信通知");
            deliveryService.sendMsg2user(order,1);
            logger.info("【drug模块-支付宝支付监听】" + orderNo + "发送支付成功消息");

            logger.info("【drug模块-支付宝支付监听】更新配送订单数据结束");

            if(StringUtils.isNotBlank(delivery.getDrugOrderNo())){
                /**调用接口推送订单信息**/
                Map<String, String> pushMap = new HashMap<String, String>();
                pushMap.put("order_no", order.getOrderNo());
                pushMap.put("check_status", "0");
                Response pushResponse = DrugService.callUnderlineFromInternal("yyt.drug.order.item.out.push", JsonUtils.toJsonString(pushMap));
                logger.info("【drug模块-支付宝支付监听】订单推送, yyt.drug.order.item.out.push, pushResponse="+ JSON.toJSONString(pushResponse));
                if(!"0".equals(pushResponse.getResultCode())){
                    logger.error("【drug模块-支付宝支付监听】订单推送失败：" + pushResponse.getResultMessage());
                    delivery.setOperationResponse("支付宝支付监听-订单推送失败：" + JSON.toJSONString(pushResponse));
                }else{
                    logger.info("【drug模块-支付宝支付监听】订单推送成功");
                    delivery.setOperationResponse("支付宝支付监听-订单推送成功：" + JSON.toJSONString(pushResponse));
                }
                deliveryService.updateDeliveryInner(delivery);
            }

        } catch (Exception e) {
            e.printStackTrace();
            Delivery delivery = deliveryService.selectByOrderNo(orderNo);
            delivery.setOperationResponse("支付宝支付监听异常：" + e.getMessage());
            deliveryService.updateDeliveryInner(delivery);
            logger.error("【drug模块-支付宝支付监听】onMessage error=", e.getMessage());
        }

        logger.info("【drug模块-支付宝支付监听】onMessage end.");
    }


}
